package com.tensquare.article.controller;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Comment;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.tensquare.article.pojo.Article;
import com.tensquare.article.service.ArticleService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;

import javax.servlet.http.HttpServletRequest;

/**
 * 文章控制器层
 * @author Administrator
 *
 */
@RestController
@CrossOrigin
@RequestMapping("/article")
public class ArticleController {

	@Autowired
	private ArticleService articleService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private RedisTemplate redisTemplate;
	
	
	/**
	 * 查询全部数据
	 * @return
	 */
	@RequestMapping(method= RequestMethod.GET)
	public Result findAll(){
		return new Result(true,StatusCode.OK,"查询成功",articleService.findAll());
	}
	
	/**
	 * 根据ID查询
	 * @param id ID
	 * @return
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.GET)
	public Result findById(@PathVariable String id){
		return new Result(true,StatusCode.OK,"查询成功",articleService.findById(id));
	}


	/**
	 * 分页+多条件查询
	 * @param searchMap 查询条件封装
	 * @param page 页码
	 * @param size 页大小
	 * @return 分页结果
	 */
	@RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
	public Result findSearch(@RequestBody Map searchMap , @PathVariable int page, @PathVariable int size){
		Page<Article> pageList = articleService.findSearch(searchMap, page, size);
		return  new Result(true,StatusCode.OK,"查询成功",  new PageResult<Article>(pageList.getTotalElements(), pageList.getContent()) );
	}

	/**
     * 根据条件查询
     * @param searchMap
     * @return
     */
    @RequestMapping(value="/search",method = RequestMethod.POST)
    public Result findSearch( @RequestBody Map searchMap){
        return new Result(true,StatusCode.OK,"查询成功",articleService.findSearch(searchMap));
    }
	
	/**
	 * 增加：发表文章
	 * @param article
	 */
	@RequestMapping(method=RequestMethod.POST)
	public Result add(@RequestBody Article article  ){
		String id=articleService.add(article);
		return new Result(true,StatusCode.OK,"增加成功",id);	//把新增加的文章id传给前端
	}
	
	/**
	 * 修改文章
	 * @param article
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.PUT)
	public Result update(@RequestBody Article article, @PathVariable String id ){
		article.setId(id);
		articleService.update(article);		
		return new Result(true,StatusCode.OK,"修改成功");
	}
	
	/**
	 * 删除文章
	 * @param id
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.DELETE)
	public Result delete(@PathVariable String id ){
		articleService.deleteById(id);
		return new Result(true,StatusCode.OK,"删除成功");
	}

	/**
	 * 审核
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/examine/{id}",method=RequestMethod.PUT)
	public Result examine(@PathVariable String id){
		articleService.examine(id);
		return new Result(true, StatusCode.OK, "审核成功");
	}

	/**
	 * 点赞1，不可以重复点赞
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/thumbup1/{id}",method=RequestMethod.PUT)
	public Result updateThumbup(@PathVariable String id){
		articleService.updateThumbup(id);
		return new Result(true, StatusCode.OK,"点赞成功");
	}

	//根据频道id获取文章列表 /channel/id/page/size
	@RequestMapping(value = "/channel/{id}/{page}/{size}",method = RequestMethod.POST)
	public Result getListByChannel(@RequestBody Map searchMap,@PathVariable String id,@PathVariable int page,@PathVariable int size){
		Page<Article> pageList=articleService.getListByChannel(searchMap,id,page,size);
		return new Result(true,StatusCode.OK,"查询成功",
				new PageResult<Article>(pageList.getTotalElements(), pageList.getContent()));
	}
	//根据专栏id获取文章列表 column/id/page/size
	@RequestMapping(value = "/column/{id}/{page}/{size}",method = RequestMethod.POST)
	public Result getListByColumn(@RequestBody Map searchMap,@PathVariable String id,@PathVariable int page,@PathVariable int size){
		Page<Article> pageList=articleService.getListByColumn(searchMap,id,page,size);
		return new Result(true,StatusCode.OK,"查询成功",
				new PageResult<Article>(pageList.getTotalElements(), pageList.getContent()));
	}
	//文章和标签列表的绑定
	@RequestMapping(value = "/labels/{aid}",method = RequestMethod.POST)
	public Result setArticleLabels(@PathVariable String aid,@RequestBody List<String> labels){
		for(String labelid:labels){
			articleService.setArticleLabel(aid,labelid);
		}
		return new Result(true,StatusCode.OK,"插入标签成功");
	}
	//头条文章	/top

	//获取文章的评论列表
	@RequestMapping(value = "/article_comments/{aid}",method = RequestMethod.GET)
	public Result getArticleComments(@PathVariable String aid){
		List<Comment> list=articleService.getArticleComments(aid);
		return new Result(true,StatusCode.OK,"查询成功",list);
	}
	//获取评论的评论列表
	@RequestMapping(value = "/comment_comments/{cid}",method = RequestMethod.GET)
	public Result getCommentComments(@PathVariable String cid){
		List<Comment> list=articleService.getCommentComments(cid);
		return new Result(true,StatusCode.OK,"查询成功",list);
	}
	//根据评论id获取评论详情
	@RequestMapping(value = "/commentById/{id}",method = RequestMethod.GET)
	public Result getCommentById(@PathVariable String id){
		Comment comment =articleService.getCommentById(id);
		return new Result(true,StatusCode.OK,"查询成功",comment);
	}

	//添加文章和评论的评论
	@RequestMapping(value = "/setComment",method = RequestMethod.POST)
	public Result setComment(@RequestBody Comment comment){
		articleService.setComment(comment);
		return new Result(true,StatusCode.OK,"评论成功");
	}

	//根据文章id订阅文章的作者，或者取消订阅
	@RequestMapping(value = "/subscribe", method = RequestMethod.POST)
	public Result subscribe(@RequestBody Map map) {
		//根据文章id，订阅文章作者，返回订阅状态，true表示订阅成功，false表示取消订阅成功
		//userId是当前登录的用户id
		Boolean flag = articleService.subscribe(map.get("userId").toString(), map.get("articleId").toString());
		if (flag) {
			System.out.println("订阅文章作者成功！");
			return new Result(true, StatusCode.OK, "订阅成功");
		} else {
			System.out.println("取消订阅文章作者成功！");
			return new Result(true, StatusCode.OK, "订阅取消");
		}
	}

	//文章点赞
	@RequestMapping(value = "/thumbup/{articleId}", method = RequestMethod.PUT)
	public Result thumbup(@PathVariable String articleId){
		//通过jwt获得当前登录的用户id
		Claims user_claims = (Claims)request.getAttribute("user_claims");
		String userId = user_claims.getId();
		String key = "thumbup_article_" + userId + "_" + articleId;		//存储是否已经点赞
		//查询用户点赞信息，根据用户id和文章id
		Object flag = redisTemplate.opsForValue().get(key);
		//判断查询到的结果是否为空
		if (flag == null) {
			//如果为空，表示用户没有点过赞，可以点赞
			articleService.thumbup(articleId,userId);
			//点赞成功，保存点赞信息
			redisTemplate.opsForValue().set(key, 1);
			return new Result(true, StatusCode.OK, "点赞成功");
		}
		//如果不为空，表示用户点过赞，不可以重复点赞
		return new Result(false, StatusCode.REPERROR, "不能重复点赞");
	}

	//查询我订阅的作者的列表
	@RequestMapping(value = "/getMyFollowers",method = RequestMethod.GET)
	public Result getMyFollowers(){
		Claims user_claims = (Claims)request.getAttribute("user_claims");
		String userId = user_claims.getId();
		if(userId==null||userId.equals("")) return  new Result(false,StatusCode.ERROR,"当前用户未登录",null);
		String userKey = "article_subscribe_" +userId;
		Set members = redisTemplate.boundSetOps(userKey).members();
		return  new Result(true,StatusCode.OK,"查询成功",members);
	}

	//测试，获取文章所有列表，去掉文章标题的h1标签
	@RequestMapping(value = "/setTitle",method = RequestMethod.GET)
	public Result setTitle(){
		String htmlRegex="<[^>]+>";
		List<Article> all = articleService.findAll();
		for(Article a :all){
			a.setTitle(a.getTitle().replaceAll(htmlRegex,""));
			System.out.println(a.getId());
			articleService.update(a);
		}
		return  new Result(true,StatusCode.OK,"设置成功");
	}

	//根据用户id，查询他的其他四篇文章
	@RequestMapping(value = "/otherArticles/{uid}/{aid}",method = RequestMethod.GET)
	public Result getOtherArticles(@PathVariable String uid,@PathVariable  String aid){
		//System.out.println(uid+":"+aid);
		List<String> list= articleService.getOtherArticles(uid,aid);
		//System.out.println(list);
		return  new Result(true,StatusCode.OK,"查询成功",list);
	}

	//查询热门文章
	@RequestMapping(value = "/hotArticles",method = RequestMethod.GET)
	public Result getHotArticles(){
		List<String> list=articleService.getHotArticles();
		return  new Result(true,StatusCode.OK,"查询成功",list);
	}

	//查询我的文章列表，分页
	@RequestMapping(value = "/myArticles/{page}/{size}",method = RequestMethod.GET)
	public Result getMyArticles(@PathVariable int page,@PathVariable int size){
		Claims user_claims = (Claims)request.getAttribute("user_claims");
		String userId = user_claims.getId();
		if(userId==null||userId.equals("")) return  new Result(false,StatusCode.ERROR,"当前用户未登录",null);
		Page<Article> pageList=articleService.getMyArticles(userId,page,size);
		return  new Result(true,StatusCode.OK,"查询成功",new PageResult<Article>(pageList.getTotalElements(), pageList.getContent()));
	}
}
